package com.alison;

import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class YamlMapSourceFactory implements PropertySourceFactory {
//    @Override
//    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
//        YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean();
//        yamlMapFactoryBean.setResources(resource.getResource());
//        yamlMapFactoryBean.afterPropertiesSet();
//        Map<String, Object> map = yamlMapFactoryBean.getObject();
//        return new MapPropertySource(name, map);
//    }

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}